package com.hhit.collaborative_learning.management;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.hhit.collaborative_learning.dao.impl.PublicDaoImplMySql;
import com.hhit.collaborative_learning.entity.User;
import com.hhit.collaborative_learning.utils.Utils;
import com.mysql.jdbc.StringUtils;

@MultipartConfig
public class RegisterServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String email=request.getParameter("email");
		String nickName=request.getParameter("nickname");
		String link=request.getParameter("link");
		link=URLDecoder.decode(link, "utf-8");
		link=StringUtils.isNullOrEmpty(link)?"learning/learning.jsp":link;
		String filename="";
		Part file=request.getPart("file");
		if(file!=null&&!StringUtils.isNullOrEmpty(file.getName().trim())&&file.getSize()>0){
			if(file.getSize()>1024*1024){
				response.setHeader("refresh", "3;url="+request.getContextPath()+"/register.jsp");
				request.setAttribute("msg", "您上传的图片大于1M,请重新上传!");
				request.getRequestDispatcher("/fail.jsp").forward(request, response);
				return;
			}
			String path = getServletContext().getRealPath("/userIcons");
			filename=Utils.saveImage(path, file);
		}
		PublicDaoImplMySql dao=new PublicDaoImplMySql();
		User user=dao.register(username, password, email, filename,nickName);
		if(user!=null){
			Cookie userId=new Cookie("userId", user.userId+"");
			userId.setPath("/");
			response.addCookie(userId);
			
			Cookie userIcon=new Cookie("userIcon", user.userIcon);
			userId.setPath("/");
			response.addCookie(userIcon);
			
			Cookie userNickName=new Cookie("userNickName", URLEncoder.encode(user.userNickName, "utf-8"));
			userId.setPath("/");
			response.addCookie(userNickName);
			response.setContentType("text/html");
			
			PrintWriter out= response.getWriter();
			out.println("即使通信 注册...<br>");
			out.println("<script type='text/javascript'> alert('a');</script>");
			response.sendRedirect(link);
		}else{
			System.out.println("false");
		}
	}
	
}
